<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <button>get请求</button>
  <button>get请求-id/name</button>
  <button>post请求</button>
  <script>

    function $ajaxGet (url, data) {
      return new Promise((resolve, reject) => {
        let xhr = new XMLHttpRequest();
        xhr.onreadystatechange = () => {
          if (xhr.readyState == 4) {
            if (xhr.status == 200 && xhr.status < 300 | xhr.status == 304) {
              resolve(xhr.responseText)
            } else {
              reject('请求失败')
            }
          }
        }
        xhr.open("GET", url)
        xhr.send()
      })
    }
    function $ajaxPost (url, data) {
      return new Promise((resolve, reject) => {
        let xhr = new XMLHttpRequest();
        xhr.onreadystatechange = () => {
          if (xhr.readyState == 4) {
            if (xhr.status == 200 && xhr.status < 300 | xhr.status == 304) {
              resolve(xhr.responseText);
            } else {
              reject("请求失败")
            }
          }
        }
        xhr.open("POST", url)
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
        xhr.send(data)
      })
    }

    document.querySelectorAll('button')[0].addEventListener('click', () => {
      $ajaxGet("http://localhost:3008/api/student/getStudent").then(result => {
        console.log(result);
      }).catch(err => {
        console.log(err);
      }).finally(() => {
        console.log("成功或失败都会执行");

      })
    })
    document.querySelectorAll('button')[1].addEventListener('click', () => {
      $ajaxGet("http://localhost:3008/api/student/getStudent?id=1607417640348").then(result => {
        console.log(result);
      }).catch(err => {
        console.log(err);
      }).finally(() => {
        console.log("成功或失败都会执行");
      })
    })
    document.querySelectorAll('button')[2].addEventListener('click', () => {
      $ajaxPost("http://localhost:3008/api/student/addStudent", "class=朱朵朵&age=18&gender=女&hobby=睡觉&address=郑州")
        .then(result => {
          console.log(result);
        }).catch(error => {
          console.log(error);
        }).finally(() => {
          console.log('都会执行的函数');
        })
    })

  </script>
</body>

</html>